Page({
  data: {
    user: {},
    orderList: [],
    totalIncome: 0.0,
    hasData: true,
    timestamp1:'',
  },

  onShow() {
    const user = wx.getStorageSync('user') || {};
    this.setData({ user });
    this.getOrderList(user)
  },

  getOrderList(user) {
    // 根据用户 ID 查询匹配的订单信息
    wx.cloud.database().collection('zyzl_shopcart').where({
      user: user
    }).get().then(res => {
      if (res.data && res.data.length > 0) {
        // 将订单列表按倒序排列
        const orderList = res.data.reverse().map(order => {
          order.timestamp = this.formatTimestamp(order.timestamp);
          return order;
        });
        // 计算订单合计
        const totalIncome = orderList.reduce((total, order) => total + order.price, 0);
        this.setData({ orderList, totalIncome });
      } else {
        this.setData({ hasData: false });
      }
    }).catch(err => {
      console.error('获取订单信息失败', err);
    });
  },

  formatTimestamp(timestamp) {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  searchOrder(e) {
    const value = e.detail.value.trim(); // 获取搜索框输入的值，去除前后空格
    const { orderList } = this.data;

    // 根据订单编号或目的地进行筛选
    const filteredOrders = orderList.filter(order => {
      return order._id.includes(value) || order.name.includes(value);
    });

    this.setData({ orderList: filteredOrders });
  }

});
